"""
问题2完整求解程序 - 同尺寸定日镜场的优化设计
目标: 在满足功率≥60MW约束下，找到最优的定日镜场设计方案

按照题目流程实现:
阶段1: 参数化布局生成 (快速构建可行解)
阶段2: 外层优化 (差分进化算法) 
阶段3: 内层优化 (局部微调与约束修复)
阶段4: 光学效率计算 (复用问题一模块)
"""

import time
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
from problem2_solver_enhanced import Problem2SolverEnhanced

def main():
    """问题2主求解程序"""
    print("="*80)
    print("🏗️  数学建模竞赛 - 问题2求解程序")
    print("📋 目标: 同尺寸定日镜场的优化设计 (功率≥60MW)")
    print("🔄 算法: 分层优化策略 (参数化布局 + 差分进化 + 局部微调)")
    print("="*80)
    
    # 创建求解器
    solver = Problem2SolverEnhanced()
    
    # 执行完整求解
    try:
        start_time = time.time()
        result = solver.solve_problem2()
        total_time = time.time() - start_time
        
        if result is not None:
            print("\n" + "="*80)
            print("🎉 问题2求解成功!")
            print("="*80)
            
            # 输出最优解
            xT, yT, w, h, hm = result['solution'][:5]
            power = result['power']
            efficiency = result['efficiency']
            num_mirrors = result['num_mirrors']
            
            print(f"📊 最优设计方案:")
            print(f"   吸收塔位置: ({xT:.2f}, {yT:.2f}) m")
            print(f"   定日镜尺寸: {w:.2f} × {h:.2f} m")
            print(f"   安装高度: {hm:.2f} m")
            print(f"   定日镜数量: {num_mirrors}")
            print(f"   总输出功率: {power:.2f} MW")
            print(f"   平均光学效率: {efficiency:.4f}")
            print(f"   求解用时: {total_time:.1f} 秒")
            
            # 约束验证
            print(f"\n📋 约束条件验证:")
            print(f"   功率要求 (≥60MW): {'✅' if power >= 60 else '❌'} ({power:.2f} MW)")
            print(f"   镜面尺寸约束: {'✅' if 2 <= h <= w <= 8 else '❌'} ({w:.2f} × {h:.2f} m)")
            print(f"   安装高度约束: {'✅' if 2 <= hm <= 6 else '❌'} ({hm:.2f} m)")
            tower_distance = (xT**2 + yT**2)**0.5
            print(f"   塔位置约束: {'✅' if tower_distance <= 350 else '❌'} (距离: {tower_distance:.2f} m)")
            
            # 性能指标
            total_area = num_mirrors * w * h
            power_density = power / (total_area / 1e6)  # MW/km²
            print(f"\n📈 性能指标:")
            print(f"   镜面总面积: {total_area:.0f} m²")
            print(f"   功率密度: {power_density:.2f} MW/km²")
            print(f"   镜面利用率: {efficiency:.1%}")
            
            # 保存结果到文件
            save_results(result, total_time)
            
            # 生成可视化
            print(f"\n🎨 生成可视化...")
            solver.visualize_result(result)
            
        else:
            print("\n❌ 问题2求解失败!")
            print("   可能原因:")
            print("   - 约束条件过于严格")
            print("   - 优化算法未收敛到可行解")
            print("   - 功率要求无法满足")
            
    except Exception as e:
        print(f"\n💥 求解过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

def save_results(result, solve_time):
    """保存求解结果到文件"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"problem2_result_{timestamp}.txt"
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write("="*60 + "\n")
        f.write("数学建模竞赛 - 问题2求解结果\n")
        f.write("同尺寸定日镜场的优化设计\n")
        f.write("="*60 + "\n")
        f.write(f"求解时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"求解用时: {solve_time:.1f} 秒\n\n")
        
        # 最优解参数
        xT, yT, w, h, hm = result['solution'][:5]
        r_rings = sorted(result['solution'][5:]) if len(result['solution']) > 5 else []
        
        f.write("最优设计方案:\n")
        f.write(f"  吸收塔位置: ({xT:.3f}, {yT:.3f}) m\n")
        f.write(f"  定日镜尺寸: {w:.3f} × {h:.3f} m\n")
        f.write(f"  安装高度: {hm:.3f} m\n")
        f.write(f"  定日镜数量: {result['num_mirrors']}\n")
        f.write(f"  总输出功率: {result['power']:.3f} MW\n")
        f.write(f"  平均光学效率: {result['efficiency']:.6f}\n")
        
        if r_rings:
            f.write(f"  环半径配置: {[f'{r:.1f}' for r in r_rings]}\n")
        
        f.write("\n")
        
        # 约束检查
        f.write("约束条件检查:\n")
        f.write(f"  功率要求 (≥60MW): {'✅' if result['power'] >= 60 else '❌'} ({result['power']:.2f} MW)\n")
        f.write(f"  镜面尺寸约束: {'✅' if 2 <= h <= w <= 8 else '❌'} ({w:.2f} × {h:.2f} m)\n")
        f.write(f"  安装高度约束: {'✅' if 2 <= hm <= 6 else '❌'} ({hm:.2f} m)\n")
        tower_distance = (xT**2 + yT**2)**0.5
        f.write(f"  塔位置约束: {'✅' if tower_distance <= 350 else '❌'} (距离: {tower_distance:.2f} m)\n")
        
        # 性能分析
        total_area = result['num_mirrors'] * w * h
        power_density = result['power'] / (total_area / 1e6)
        
        f.write(f"\n性能分析:\n")
        f.write(f"  镜面总面积: {total_area:.0f} m²\n")
        f.write(f"  功率密度: {power_density:.2f} MW/km²\n")
        f.write(f"  场地利用率: {total_area / (np.pi * 350**2):.1%}\n")
        f.write(f"  镜面利用率: {result['efficiency']:.1%}\n")
        
        # 布局配置
        f.write(f"\n布局配置:\n")
        f.write(f"  布局类型: 环交错布局\n")
        f.write(f"  环数: {len(r_rings) if r_rings else '未知'}\n")
        f.write(f"  最内环半径: {r_rings[0]:.1f} m\n" if r_rings else "")
        f.write(f"  最外环半径: {r_rings[-1]:.1f} m\n" if r_rings else "")
        
        f.write("\n" + "="*60 + "\n")
        f.write("算法说明:\n")
        f.write("阶段1: 参数化布局生成 (环交错布局)\n")
        f.write("阶段2: 外层优化 (差分进化算法)\n")
        f.write("阶段3: 内层优化 (局部微调与约束修复)\n")
        f.write("阶段4: 光学效率计算 (复用问题一模块)\n")
        f.write("="*60 + "\n")
    
    print(f"\n💾 结果已保存到: {filename}")

def quick_test():
    """快速测试模式"""
    print("🚀 快速测试模式")
    solver = Problem2SolverEnhanced()
    
    # 使用简化参数进行快速测试
    xT, yT, w, h, hm = 0, 0, 6, 4, 4
    r_rings = [120, 150, 180, 220, 260, 300]
    
    print("🔄 测试布局生成...")
    positions = solver.generate_layout(xT, yT, w, h, hm, r_rings)
    print(f"✅ 生成 {len(positions)} 个定日镜位置")
    
    print("🔄 测试约束检查...")
    feasible, power, efficiency = solver._check_constraints(xT, yT, w, h, hm, positions)
    print(f"✅ 约束检查: {'可行' if feasible else '不可行'}")
    print(f"   功率: {power:.2f} MW")
    print(f"   效率: {efficiency:.4f}")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == "--test":
        quick_test()
    else:
        main() 